package com.zut.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.zut.auth.application.convert.AuthUserDTOConverter;
import com.zut.auth.application.dto.AuthUserDTO;

import com.zut.common.entity.Result;
import com.zut.domain.entity.AuthUserBO;
import com.zut.domain.sevice.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/user/")
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;
    /**
     * 用户注册
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        Result result =new Result();
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            checkUserInfo(authUserDTO);
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            return result.success(authUserDomainService.register(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return result.fail("注册用户失败");
        }
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        Result result =new Result();
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            checkUserInfo(authUserDTO);
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            return result.success(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return result.fail("更新用户信息失败");
        }
    }

    /**
     * 获取用户信息
     */
    @RequestMapping("getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        Result result =new Result();
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            //校验用户名不能为空
            checkUserInfo(authUserDTO);

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            AuthUserBO authUserBO1=authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO authUserDTO1 = AuthUserDTOConverter.INSTANCE.convertBOToDTO(authUserBO1);
            return result.success(authUserDTO1);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return result.fail("更新用户信息失败");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        Result result=new Result();
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDTO));
            }
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            return result.success(authUserDomainService.delete(authUserBO));
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return result.fail("删除用户信息失败");
        }
    }

    private void checkUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
    }

//
//
//
    /**
     * 用户启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        Result result=new Result();
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            return result.success(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return result.fail("启用/禁用用户信息失败");
        }
    }

    /**
     * 用户登出
     * @return
     */
    @RequestMapping("logOut")
    public Result logOut(@RequestParam String userName) {

        try {
            Result result=new Result<>();
            log.info("UserController.logOut:{}",userName);
            Preconditions.checkArgument(!StringUtils.isBlank(userName),"您所查询的用户名为空！");

            StpUtil.logout(userName);
            return result.success("用户退出登录成功！");


        } catch (Exception e) {
            Result<String> result=new Result<>();
            log.error("UserController.logOut.error:{}",e.getMessage(),e);
            return result.fail("用户退出登录失败");
        }
    }



    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {

        try {
            Result<SaTokenInfo> result=new Result<>();
            // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
            Preconditions.checkArgument(!StringUtils.isBlank(validCode),"您所输入验证码为空！");
            SaTokenInfo saTokenInfo=authUserDomainService.doLogin(validCode);
            return result.success(saTokenInfo);

        } catch (Exception e) {
            Result<String> result=new Result<>();
            log.error("UserController.changeStatus.error:{}",e.getMessage(),e);
            return result.fail("用户登录失败");
        }

//        if("zhang".equals(username) && "123456".equals(password)) {
//            StpUtil.login("鸡翅");
//            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//            return SaResult.data(tokenInfo);
//        }
//        return SaResult.error("登录失败");
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

}
